package com.java1412.controller.api;

import com.java1412.entity.User;
import com.java1412.service.CartService;
import com.java1412.utils.ConstantUtil;
import com.java1412.utils.ResponseUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author java1412
 * @since 2023-08-10 09:28:06
 */
@RestController
@RequestMapping(value = "/api/cart")
public class CartController {

    @Resource
    private CartService cartService;

    @GetMapping(value = "/findCount")
    public Object findCount(
            HttpSession session
    ) {
        // 获取当前登录的用户
        User loginUser = (User) session.getAttribute(ConstantUtil.LOGIN_USER_KEY);
        // 获取登录用户的id
        Integer userId = loginUser.getId();
        // 根据登录的用户id查询购物车数量
        ResponseUtil r = cartService.findCountByUserId(userId);
        return r;
    }

    @GetMapping(value = "/find")
    public Object find(
            HttpSession session
    ) {
        // 获取当前登录的用户
        User loginUser = (User) session.getAttribute(ConstantUtil.LOGIN_USER_KEY);
        // 获取登录用户的id
        Integer userId = loginUser.getId();
        // 根据登录的用户id查询购物车数量
        ResponseUtil r = cartService.findByUserId(userId);
        return r;
    }

    @PostMapping(value = "/updateCart")
    public Object updateCart(
            @RequestParam(value = "id", required = true) Integer id,
            @RequestParam(value = "quantity", required = true) Integer quantity,
            @RequestParam(value = "checked", required = true) Integer checked
    ) {
        ResponseUtil r = cartService.updateCart(id, quantity, checked);
        return r;
    }

    /**
     * 根据id删除购物车
     */
    @GetMapping(value = "/deleteById/{id}")
    public ResponseUtil deleteById(@PathVariable("id") Integer id) {
        return cartService.deleteById(id);
    }

    /**
     * 批量删除
     *
     * @param strIds
     * @return
     */
    @GetMapping(value = "/deleteBatch")
    public ResponseUtil deleteBatch(@RequestParam("strIds") String strIds) {
        ResponseUtil r = null;
        if (null == strIds) {
            r = ResponseUtil.fail("批量删除购物车失败");
        } else {
            String[] ids = strIds.split(",");
            List<Integer> deleteIds = new ArrayList<>();
            for (String id : ids) {
                deleteIds.add(Integer.parseInt(id));
            }
            deleteIds.forEach(System.out::println);
            r = cartService.deleteBatch(deleteIds);
        }
        return r;
    }
}
